package com.qudian.java.core.common.utils;

import com.qudian.java.core.common.annotation.Validate;
import com.qudian.java.core.common.enumeration.ValidateEnum;
import com.qudian.java.core.common.exception.BusinessException;
import com.qudian.java.core.common.exception.ErrorCodeEnum;
import org.springframework.util.StringUtils;
import com.qudian.java.core.common.enumeration.RegexTypeEnum;

import java.lang.reflect.Field;

/**
 * Created by zhangdelong on 16/8/27.
 * 基本参数校验
 * 参数校验,传参:对象,
 */

public class BaseParamValidate {

    private static Validate validate;

    public static void validate(Object object) throws BusinessException, Exception {

        //获取object的类型
        Class<? extends Object> clazz = object.getClass();
        //获取该类型声明的成员
        Field[] fields = clazz.getDeclaredFields();
        //遍历属性
        for (Field field : fields) {
            //对于private私有化的成员变量，通过setAccessible来修改器访问权限
            field.setAccessible(true);
            valid(field, object);
            //重新设置会私有权限
            field.setAccessible(false);
        }
    }

    protected static void valid(Field field, Object object) throws BusinessException, Exception {
        String description;
        Object value;
        //获取对象的成员的注解信息
        validate = field.getAnnotation(Validate.class);
        value = field.get(object);
        if (validate == null) {
            return;
        }
        description = ObjectUtil.isEmpty(validate.description()) ? field.getName() : validate.description();
        // 非空校验
        if (validate.isNotNull()){
            if (StringUtils.isEmpty(value)){
             throw new BusinessException(ErrorCodeEnum.BIZ_ERROR_0001.getCode(),description+ ValidateEnum.NotNull.getName());
            }
        }
        //按照正则校验
        if (validate.regexType()!= RegexTypeEnum.NONE){
            switch (validate.regexType()){
                case NONE:break;
                case RealNumber:
                    if (!RegexUtils.isRealNumber(value.toString())){
                        throw new BusinessException(ErrorCodeEnum.BIZ_ERROR_0001.getCode(),description+ValidateEnum.formatError.getName());
                    }
                    break;
            }
        }
    }

}
